#include <stdio.h>
#include <gccore.h>

#include "FakeSignInstaller.h"
#include "../build/cert_sys.h"
#include "controller.h"
#include "tools.h"
#include "video.h"
#include "signcheckfunctions.h"
#include "IOSPatcher.h"
#include "wiibasics.h"
#include "gecko.h"

int FakeSignInstall()
{	
	int ret;

	// Let's see if we are already on IOS36, if not then reload to IOS36
	if (IOS_GetVersion() != 36) 
	{
		gcprintf("Momentan geladene IOS ist nicht 36. Lade IOS36...\n");
		ret = ReloadIos(36);
		if (ret < 0)
		{
			gcprintf("Fehler: IOS36 laden fehlgeschlagen (%d)", ret);
			return ret;
		}
	}

	gprintf("Hole certs.sys vom NAND um f\x81 \br FakeSign zu testen...");
	ret = GetCert();
	if (ret < -1) 
	{
		gcprintf("Fehler (%d)\n", ret);
		return ret;
	}		
	gprintf("\n");
	
	// Lets see if version is already fakesigned
	gprintf("Teste FakeSign an IOS36\n");
	if (CheckFakeSign())
	{
		gcprintf("\n\nIOS36 ist bereits FakeSign gepatcht.\n");
		return -1;
	}
	gprintf("TesteFakeSign = %d", ret);	

	// Downgrade IOS 15
	gcprintf("*** Downgrade von IOS15 auf r257 ***\n");
	ret = IosDowngrade(15, IOS15Version, 257);
	if (ret < 0)
	{
		gcprintf("Fehler: Downgrade von IOS15 fehlgeschlagen (%d)\n", ret);
		return ret;
	}

	// Install IOS36 but ask if they want ES_Identity and NAND Patches installed.
	gcprintf("\n*** Installiere IOS36 (r%d) mit FakeSign ***\n", IOS36Version);
	// Load IOS 15
	gcprintf("Lade IOS15 (r257)...");	
	SpinnerStart();
	ret = ReloadIos(15);
	SpinnerStop();
	if (ret < 0)
	{
		gcprintf("Fehler: Laden von IOS15 fehlgeschlagen (%d)", ret);
		return ret;
	}
	gcprintf("\b.Fertig\n");

	printf("\nES_Identify Patch an IOS36 durchf\x81 \bhren?\n");
	bool esIdentifyPatch = PromptYesNo();

	printf("\nNAND Erlaubnis Patch an IOS36 durchf\x81 \bhren?\n");
	bool nandPatch = PromptYesNo();

	gcprintf("\n");
	ret = IosInstall(36, IOS36Version, true, esIdentifyPatch, nandPatch);
	if (ret < 0)
	{
		gcprintf("Installieren von IOS36 fehlgeschlagen (%d)", ret);
		return ret;
	}

	// Load IOS 36 to restore IOS 15
	gcprintf("\n*** Stelle IOS15 (r%d) wieder her ***\n", IOS15Version);
	gcprintf("Lade IOS36 (r%d)...", IOS36Version);
	SpinnerStart();
	ret = ReloadIos(36);
	SpinnerStop();
	if (ret < 0)
	{
		gcprintf("Fehler: Laden von IOS36 fehlgeschlagen (%d)", ret);
		return ret;
	}
	gcprintf("\b.Fertig\n");

	ret = IosInstallUnpatched(15, IOS15Version);
	if (ret < 0)
	{
		gcprintf("Erneutes installieren von IOS15 fehlgeschlagen. (%d)", ret);
		return ret;
	}

	return 1;
}